package com.youmu.sichuansfc.filter.FundManager;

import com.youmu.sichuansfc.ano.FundManager.FundUserAuth;
import com.youmu.sichuansfc.common.CommonRes;
import com.youmu.sichuansfc.domain.YoumuFundUser;
import com.youmu.sichuansfc.service.FundUserService;
import com.youmu.sichuansfc.util.Const;
import com.youmu.sichuansfc.util.CookieUtil;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 *  登录 拦截器
 * @author Administrator
 *
 */
@Component  
public class LoginInterceptor extends HandlerInterceptorAdapter {
	
	private static Logger logger = Logger.getLogger(LoginInterceptor.class);

	@Autowired
    public FundUserService fundUserService;

    public boolean preHandle(HttpServletRequest request,  
                             HttpServletResponse response, Object handler) throws Exception {
        logger.info("进入拦截器");
        // FIXME
        response.setHeader("Access-Control-Allow-Credentials", "true");
        logger.info(fundUserService + " is  fundUserService");

        //解决Autowired为null无法注入问题
        if (fundUserService == null) {
            WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getAutowireCapableBeanFactory().autowireBean(this);
            logger.info(fundUserService + " is  fundUserService");
        }

        final HandlerMethod handlerMethod = (HandlerMethod) handler;  
        final Method method = handlerMethod.getMethod();
        final Class<?> clazz = method.getDeclaringClass();
        if (clazz.isAnnotationPresent(FundUserAuth.class) || method.isAnnotationPresent(FundUserAuth.class)) {
        	YoumuFundUser fundUser = handlerWAWATOKEN(request, fundUserService);
        	if(fundUser != null) {
                logger.info("TOKEN  用户 name = " + fundUser.getName() + " / id = " + fundUser.getId() + " / token = " + fundUser.getToken());
            }
            // FIXME
            if(fundUser  == null ){
            	logger.info(" 401 异常 TOKEN = " );

            	//重定向到登录页
				response.setCharacterEncoding("utf-8");
				response.setContentType("application/json;charset=utf-8");
				response.sendError(401);
				response.setStatus(401);
				PrintWriter out = response.getWriter();

				out.print(new JSONObject(CommonRes.checkFail("未授权")));
				out.flush();
				return false;
            }else{  
               
            }  
        }  
        return true;  
    }

    /**
     *  校验 token 用户是否登录
     * @param request
     * @return
     */
    public YoumuFundUser handlerWAWATOKEN(HttpServletRequest request, FundUserService fundUserService1) {
        logger.info(" 取 token= 开始");
        try {

            String fund_user_token = new CookieUtil(request).getCookieByName(Const.FUND_USER_TOKEN);

            logger.info(" 登录校验 fund_user_token = "+ fund_user_token);

            if (fund_user_token != null && !"".equals(fund_user_token) ) {
                YoumuFundUser youmuFundUser = fundUserService1.findByToken(fund_user_token);
                return youmuFundUser;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }  
} 